package org.example.trigger.listener;


import com.alibaba.fastjson2.JSON;

import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;

import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.example.domain.activity.service.IActivitySkuStock;
import org.example.types.event.BaseEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 活动sku库存为0消息消费者
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "sst-group-activity-sku-stock-zero", topic = "activity_sku_stock_zero")
public class ActivitySkuStockZeroCustomer implements RocketMQListener<String> {

    private String topic = "activity_sku_stock_zero";

    @Resource
    private IActivitySkuStock skuStock;



    @Override
    public void onMessage(String message) {
        try {
            log.info("监听活动sku库存消耗为0消息 topic: {} message: {}", topic, message);
            // 转换对象
            BaseEvent.EventMessage<Long> eventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<Long>>() {
            }.getType());
            Long sku = eventMessage.getData();
            // 更新库存
            skuStock.clearActivitySkuStock(sku);
            // 清空队列 「此时就不需要延迟更新数据库记录了」
            skuStock.clearQueueValue(sku);
        } catch (Exception e) {
            log.error("监听活动sku库存消耗为0消息，消费失败 topic: {} message: {}", topic, message);
            throw e;
        }
    }
}
